import os

import django.core.files.storage as storage

from datetime import datetime
from django.db import models
from django.contrib.auth.models import User
from ourcity.issues.models import Issue
from ourcity.reps.models import Representative


class NewsManager(models.Manager):
    def active(self):
        return self.filter(active=True)

    def recent(self, amount):
        active = self.active()
        try:
            return active[:amount]
        except IndexError:
            if active:
                return active
            return self.none()

    def most_recent(self):
        try:
            return self.recent(1)[0]
        except IndexError:
            return 

    def posts(self):
        return self.active().filter(type__name='Post')

    def reports(self):
        return self.active().filter(type__name='Report')


class NewsType(models.Model):
    name = models.CharField(max_length=64)

    def __unicode__(self):
        return self.name


class News(models.Model):
    type = models.ForeignKey(NewsType)
    title = models.CharField(max_length=128)
    subtitle = models.CharField(max_length=128, blank=True)
    slug = models.SlugField(unique=True)
    author = models.ForeignKey(User, related_name='news')
    active = models.BooleanField(default=False, 
            help_text='Mark active to publish.')
    general_news = models.BooleanField(default=False, 
            help_text="Make this news visible on every user's front page.")
    synopsis = models.TextField(blank=True, help_text='Use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> or HTML for formatting.')
    findings = models.TextField(blank=True, help_text='Use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> for formatting.')
    recommendations = models.TextField(blank=True, help_text='Use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> for formatting.')
    body = models.TextField(blank=True, help_text='Use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> or HTML for formatting.')
    create_date = models.DateTimeField(auto_now_add=True)
    pub_date = models.DateTimeField(blank=True, null=True, editable=False)
    issues = models.ManyToManyField(Issue, blank=True, related_name='news')
    reps = models.ManyToManyField(Representative, blank=True, 
            related_name='news')

    objects = NewsManager()

    def __unicode__(self):
        return self.title

    @models.permalink
    def get_absolute_url(self):
        if self.type.name == 'Post':
            return ('blog_post', (), {'id': self.id})
        if self.type.name == 'Report':
            return ('report', (), {'id': self.id})

    def get_author(self):
        full_name = self.author.get_full_name()
        if full_name:
            return full_name
        return self.author.username

    def is_post(self):
        return self.type.name == 'Post'

    def is_report(self):
        return self.type.name == 'Report'

    def save(self, *args, **kwargs):
        # set pub_date if marked as active and pub_date not already set
        if self.active and not self.pub_date:
            self.pub_date = datetime.now()
        super(News, self).save(*args, **kwargs)

    class Meta:
        ordering = ('-pub_date', '-id')
        verbose_name_plural = 'news'


class OverwriteStorage(storage.FileSystemStorage):
    'See http://www.djangosnippets.org/snippets/976/'
    def get_available_name(self, name):
        if self.exists(name):
            self.delete(name)
        return name


class Attachment(models.Model):
    upload = models.FileField(upload_to='uploaded/news/%Y', storage=OverwriteStorage())
    news = models.ForeignKey(News, related_name='attachments')

    def __unicode__(self):
        if self.upload:
            return os.path.basename(self.upload.name)
        else:
            return u'Unknown file'


#class Report(News):
#    subtitle = models.CharField(max_length=128, blank=True)
#    synopsis = models.TextField(help_text='Use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> or HTML for formatting.')
#    findings = models.TextField(help_text='Use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> for formatting.')
#    recommendations = models.TextField(help_text='Use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> for formatting.')
#
#    objects = NewsManager()
#
#    class Meta:
#        ordering = ('-pub_date', '-id')
#
#
#class Post(News):
#    body = models.TextField(help_text='Use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> or HTML for formatting.')
#
#    objects = NewsManager()
#
#    class Meta:
#        ordering = ('-pub_date', '-id')


#class Report(models.Model):
#    title = models.CharField(max_length=128)
#    subtitle = models.CharField(max_length=128, blank=True)
#    slug = models.SlugField(unique=True)
#    author = models.ForeignKey(User, related_name='reports')
#    synopsis = models.TextField(help_text='Use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> or HTML for formatting.')
#    findings = models.TextField(help_text='Use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> for formatting.')
#    recommendations = models.TextField(help_text='Use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> for formatting.')
#    active = models.BooleanField(default=False)
#    create_date = models.DateTimeField(auto_now_add=True)
#    pub_date = models.DateTimeField(blank=True, null=True)
#    issues = models.ManyToManyField(Issue, blank=True, related_name='reports')
#    reps = models.ManyToManyField(Representative, blank=True, 
#            related_name='reports')
#
#class ReportFile(models.Model):
#    upload = models.FileField(upload_to='uploaded/reports/%Y')
#    report = models.ForeignKey(Report, related_name='files')
#
#    def __unicode__(self):
#        if self.upload:
#            return self.upload.name
#        else:
#            return u'Unknown file'

#from datetime import datetime
#from django.db import models
#from django.contrib.auth.models import User
#from ourcity.issues.models import Issue
#from ourcity.reps.models import Representative
#
#class PostManager(models.Manager):
#    def active(self):
#        return self.filter(active=True)
#
#    def recent(self, amount):
#        active_posts = self.active()
#        try:
#            return active_posts[:amount]
#        except IndexError:
#            if active_posts:
#                return active_posts
#            return self.none()
#
#    def most_recent(self):
#        try:
#            return self.recent(1)[0]
#        except IndexError:
#            return 
#
#
#class Post(models.Model):
#    title = models.CharField(max_length=128)
#    slug = models.SlugField(unique=True)
#    author = models.ForeignKey(User, related_name='posts')
#    body = models.TextField(help_text='Use <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> or HTML for formatting.')
#    active = models.BooleanField(default=False)
#    create_date = models.DateTimeField(auto_now_add=True)
#    pub_date = models.DateTimeField(blank=True, null=True, help_text='The pub date will get filled in automatically when the post is marked as active and saved, but you can change it if you want.')
#    issues = models.ManyToManyField(Issue, blank=True, related_name='posts')
#    reps = models.ManyToManyField(Representative, blank=True, 
#            related_name='posts')
#    general_news = models.BooleanField(default=False, help_text='Make this post visible on all users\' front page.')
#
#    objects = PostManager()
#
#    def __unicode__(self):
#        return self.title
#
#    def get_author(self):
#        full_name = self.author.get_full_name()
#        if full_name:
#            return full_name
#        return self.author
#
#    def save(self, force_insert=False, force_update=False):
#        # post has been published if active is True
#        if self.active and not self.pub_date:
#            self.pub_date = datetime.now()
#        super(Post, self).save(force_insert, force_update)
#
#    class Meta:
#        ordering = ('-pub_date', '-id')
#
